﻿using System.Reflection;
using Devonline.AspNetCore;
using Devonline.Database.PostgreSQL;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Devonline.Identity.Database.PostgreSQL;

public static class ServiceExtensions
{
    /// <summary>
    /// 注册认证数据库上下文
    /// </summary>
    /// <param name="services">依赖注入服务容器</param>
    /// <param name="contextLifetime">数据库上下文的生命周期</param>
    /// <returns></returns>
    public static IServiceCollection AddPostgreSQL(this IServiceCollection services, HttpSetting httpSetting, ServiceLifetime contextLifetime = ServiceLifetime.Scoped)
    {
        if (!string.IsNullOrWhiteSpace(httpSetting.IdentityDbContext))
        {
            var assembly = httpSetting.MigrationsAssembly ?? Assembly.GetCallingAssembly().FullName;
            services.AddPostgreSQL<IdentityDbContext>(httpSetting.IdentityDbContext, assembly, contextLifetime, httpSetting.DateTimeKind);
            services.AddPostgreSQL<DataProtectionDbContext>(httpSetting.DataProtection?.ApplicationDbContext ?? httpSetting.IdentityDbContext, assembly, contextLifetime, httpSetting.DateTimeKind);
        }

        return services;
    }
    /// <summary>
    /// 注册基于安全模型的认证数据库上下文
    /// </summary>
    /// <param name="services">依赖注入服务容器</param>
    /// <param name="contextLifetime">数据库上下文的生命周期</param>
    /// <returns></returns>
    public static IServiceCollection AddPostgreSQLSecurity(this IServiceCollection services, HttpSetting httpSetting, ServiceLifetime contextLifetime = ServiceLifetime.Scoped)
    {
        if (!string.IsNullOrWhiteSpace(httpSetting.IdentityDbContext))
        {
            var assembly = httpSetting.MigrationsAssembly ?? Assembly.GetCallingAssembly().FullName;
            services.AddPostgreSQL<SecurityIdentityDbContext>(httpSetting.IdentityDbContext, assembly, contextLifetime, httpSetting.DateTimeKind);
        }

        return services;
    }

    /// <summary>
    /// 注册数据库上下文创建对象
    /// </summary>
    /// <param name="builder">依赖注入服务容器</param>
    /// <param name="connectionString">数据库连接字符串</param>
    /// <returns></returns>
    private static DbContextOptionsBuilder Build(this DbContextOptionsBuilder builder, string? connectionString = default)
    {
        return builder.UseNpgsql(connectionString, options => options.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName));
    }
}